﻿/*
Commerce by Onex – eCommerce software platform (www.ecommerce.byonex.com)
Copyright (C) 2008-2010 by Onex Group

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 
 */
using System;
using System.IO;
using System.Collections.Generic;
using System.Web;
using System.Net.Mail;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using ShopBLL;
using ShopModel;
using System.Threading;
using System.Globalization;
using System.Text.RegularExpressions;
using System.Xml;
using System.Resources;
using System.Text;

public partial class install_Default : System.Web.UI.Page
{
    #region ENUM

    protected enum InstalationError
    {
        NoError = 0,
        DatabaseNotCreated = 1,
        DatabaseIsNotEmpty = 2,
        ErrorParsingDatabaseName = 3,
        ErrorCreatingTables = 4,
        ErrorOpeningDatbaseScript = 5
    }

    #endregion ENUM

    #region VARIABLES

    protected string ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["csShop"].ConnectionString;

    #endregion VARIABLES

    #region METHODS

    private SqlConnection Connection()
    {
        return new SqlConnection(ConnectionString);
    }

    protected bool SetShopConfigXml()
    {
        string _userid = tbUserID.Text;
        string _pass = tbPass.Text;
        string _serwer = tbSerwerName.Text;
        DatabaseName = tbDBName.Text;
        string _path = Server.MapPath("~");

        XmlTextWriter xml = null;

        try
        {
            xml = new XmlTextWriter(_path + "//connection.config", Encoding.UTF8);
            xml.Formatting = Formatting.Indented;

            xml.WriteStartElement("connectionStrings");
            xml.WriteStartElement("remove");
            xml.WriteAttributeString("name", "LocalSqlServer");
            xml.WriteEndElement();
            xml.WriteStartElement("add");
            xml.WriteAttributeString("name", "LocalSqlServer");

            if (!cbWindwosAuthentication.Checked)
            {

                xml.WriteAttributeString("connectionString", String.Format("User Id={3}; Password={2}; Server={1}; Database={0};", DatabaseName, _serwer, _pass, _userid));
                xml.WriteEndElement();
                xml.WriteStartElement("add");
                xml.WriteAttributeString("name", "csShop");
                xml.WriteAttributeString("connectionString", String.Format("User Id={3}; Password={2}; Server={1}; Database={0};", DatabaseName, _serwer, _pass, _userid));
                xml.WriteEndElement();
                xml.WriteStartElement("add");
                xml.WriteAttributeString("name", "ShopConnectionString");
                xml.WriteAttributeString("connectionString", String.Format("User Id={3}; Password={2}; Server={1}; Database={0};", DatabaseName, _serwer, _pass, _userid));
            }
            else
            {
                xml.WriteAttributeString("connectionString", String.Format("Server={1}; Database={0}; Integrated Security=SSPI;", DatabaseName, _serwer));
                xml.WriteEndElement();
                xml.WriteStartElement("add");
                xml.WriteAttributeString("name", "csShop");
                xml.WriteAttributeString("connectionString", String.Format("Server={1}; Database={0}; Integrated Security=SSPI;", DatabaseName, _serwer));
                xml.WriteEndElement();
                xml.WriteStartElement("add");
                xml.WriteAttributeString("name", "ShopConnectionString");
                xml.WriteAttributeString("connectionString", String.Format("Server={1}; Database={0}; Integrated Security=SSPI;", DatabaseName, _serwer));
            }
            xml.WriteEndElement();

        }
        catch
        {
            return false;
        }
        finally
        {
            xml.Close();
        }

        return true;
    }

    protected bool AddUser()
    {
        string _user = tbAUser.Text;
        string _pass = tbAPass.Text;
        string _email = tbAEmail.Text;
        string _passQ = tbAQuestion.Text;
        string _passA = tbAAnswer.Text;

        try
        {
            MembershipCreateStatus status;
            bool emailConfirmation = ShopModel.Settings.RegistrationConfirmationMail;

            Membership.DeleteUser("admin", true);
            MembershipUser newUser = Membership.CreateUser(_user, _pass, _email, _passQ, _passA, !emailConfirmation, out status);

            if (status == MembershipCreateStatus.Success)
            {
                Roles.AddUserToRole(newUser.UserName, "administrator");
            }
            else
            {
                Membership.DeleteUser(newUser.UserName, true);
            }
        }
        catch
        {
            return false;
        }

        return true;
    }

    protected InstalationError CreateDB()
    {
        int tablesCount = -1;
        string db = string.Empty;
        SqlConnection Con = Connection();
        string cDB = string.Empty;

        try
        {
            string[] tab = ConnectionString.Split(';');

            for (int i = 0; i < tab.Length; i++)
            {
                string[] tmp = tab[i].Split('=');

                db = tmp[0].Replace(" ", "").ToLower();
                if (db == "database" || db == "inital catalog")
                {
                    db = tmp[1].Replace(" ", "");
                    break;
                }
            }

            if (db == string.Empty)
                throw new Exception();
        }
        catch
        {
            return InstalationError.ErrorParsingDatabaseName;
        }

        try
        {
            SqlCommand command = new SqlCommand("SELECT COUNT(*) FROM " + db + ".sys.tables;", Con);
            SqlDataReader sqlR;
            Con.Open();

            sqlR = command.ExecuteReader();

            if (sqlR.Read())
                tablesCount = (int)sqlR[0];

            sqlR.Close();
        }
        catch
        {
            return InstalationError.DatabaseNotCreated;
        }

        if (tablesCount == 0)
        {
            try
            {
                string temp = Server.MapPath("~/install/");
                FileStream baza = new FileStream(temp + "ShopScheme.sql", FileMode.Open);
                StreamReader file = new StreamReader(baza);
                cDB = file.ReadToEnd();
                file.Close();
            }
            catch
            {
                return InstalationError.ErrorOpeningDatbaseScript;
            }

            try
            {
                string[] statements = System.Text.RegularExpressions.Regex.Split(cDB, "\\sGO\\s", System.Text.RegularExpressions.RegexOptions.IgnoreCase);

                statements[0] = "USE [" + db + "]";

                foreach (string sql0 in statements)
                {
                    string sql = sql0.Trim();

                    if (sql.ToLower().IndexOf("setuser") >= 0)
                        continue;

                    if (sql.Length > 0)
                    {
                        using (SqlCommand cmd = new SqlCommand())
                        {
                            cmd.Connection = Con;
                            cmd.CommandType = CommandType.Text;
                            cmd.CommandText = sql.Trim();
                            cmd.ExecuteNonQuery();
                        }
                    }
                }
            }
            catch
            {
                return InstalationError.ErrorCreatingTables;
            }
        }
        else
        {
            return InstalationError.DatabaseIsNotEmpty;
        }

        return InstalationError.NoError;
    }

    protected bool SaveSettings()
    {
        try
        {
            string _path = HttpContext.Current.Server.MapPath("~");

            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(_path + "//web.config");

            XmlNode x = xmlDoc.SelectSingleNode("//configuration/location/appSettings/add[@key='ShopUrl']");

            x.Attributes.Remove(x.Attributes["value"]);
            XmlAttribute newAtt = xmlDoc.CreateAttribute("value");
            newAtt.Value = tbShopDomain.Text;
            x.Attributes.Append(newAtt);

            xmlDoc.Save(_path + "//web.config");

            switch (ddlCountry.SelectedValue)
            {
                case "1": ReportsManager.Instance.SetLanguageAsDefault(1);
                    //System.IO.File.Copy(Server.MapPath("~/App_GlobalResources/Language.en-US.resx"), Server.MapPath("~/App_GlobalResources/Language.resx"), true);
                    break;
                case "2": ReportsManager.Instance.SetLanguageAsDefault(2);
                    //System.IO.File.Copy(Server.MapPath("~/App_GlobalResources/Language.pl-PL.resx"), Server.MapPath("~/App_GlobalResources/Language.resx"), true);
                    break;
            }
        }
        catch
        {
            return false;
        }

        return true;
    }

    #endregion METHODS

    #region PROPERTIES

    private int CurrentPage
    {
        get
        {
            if (ViewState["CurrentPage"] != null)
                return (int)ViewState["CurrentPage"];
            else
                return 0;
        }

        set
        {
            ViewState["CurrentPage"] = value;
        }
    }

    public string DatabaseName
    {
        get
        {
            if (ViewState["DatabaseName"] != null)
                return (string)ViewState["DatabaseName"];
            else
                return "";
        }

        set
        {
            ViewState["DatabaseName"] = value;
        }
    }

    #endregion PROPERTIES

    #region EVENTS

    protected void btnNext_OnClick(object sender, EventArgs e)
    {
        switch (CurrentPage)
        {
            case 1:
                if (chbAccept.Checked)
                {
                    CurrentPage++;
                    chbAccept.Checked = false;
                }
                else
                    lblAcceptError.Visible = true;
                break;
            case 2:
                if (cbUseConnectionEditForm.Checked == true)
                    CurrentPage++;
                else
                {
                    CurrentPage += 2;
                }
                break;
            case 3:
                if (SetShopConfigXml())
                {
                    CurrentPage++;
                }
                else
                    CtrlShowInfo.AppendError(Resources.Language.IAutomaticConfigurationError);
                break;
            case 4:
                switch (CreateDB())
                {
                    case InstalationError.NoError:
                        CurrentPage++;
                        break;
                    case InstalationError.ErrorCreatingTables:
                        CtrlShowInfo.AppendError(Resources.Language.IinstallationError1);
                        break;
                    case InstalationError.ErrorParsingDatabaseName:
                        CtrlShowInfo.AppendError(Resources.Language.IinstallationError4);
                        break;
                    case InstalationError.DatabaseIsNotEmpty:
                        CtrlShowInfo.AppendError(Resources.Language.IinstallationError5);
                        break;
                    case InstalationError.ErrorOpeningDatbaseScript:
                        CtrlShowInfo.AppendError(Resources.Language.IinstallationError6);
                        break;
                }
                break;
            case 5:
                if (AddUser())
                {
                    CurrentPage++;

                    ddlCountry.DataSource = ShopBLL.ReportsManager.Instance.GetAvailableLanguages(true);
                    ddlCountry.DataBind();

                    switch (System.Threading.Thread.CurrentThread.CurrentUICulture.Name.ToLower())
                    {
                        case "pl-pl":
                            ddlCountry.SelectedValue = "2";
                            break;
                        case "pl":
                            ddlCountry.SelectedValue = "2";
                            break;
                        case "en-us":
                            ddlCountry.SelectedValue = "1";
                            break;
                        case "en-gb":
                            ddlCountry.SelectedValue = "1";
                            break;
                        case "en":
                            ddlCountry.SelectedValue = "1";
                            break;
                        default:
                            ddlCountry.SelectedValue = "1";
                            break;
                    }

                }
                else
                    CtrlShowInfo.AppendError(Resources.Language.IinstallationMessage4);
                break;
            case 6:
                if (SaveSettings())
                    CurrentPage++;
                else
                    CtrlShowInfo.AppendError(Resources.Language.IinstallationError3);
                break;
            case 7:
                CommonTools.UpdateInstallationStatus(CommonTools.InstallationStatus.Installed);
                Response.Redirect("~/Default.aspx");
                break;
            default:
                CtrlShowInfo.AppendError(Resources.Language.IError);
                break;
        }
    }

    protected void cbWindwosAuthentication_OnCheckedChanged(object sender, EventArgs e)
    {
        dSqlAuthentication.Visible = !cbWindwosAuthentication.Checked;
    }

    protected void LanguageChangeCommand(object sender, CommandEventArgs e)
    {
        HttpCookie cok = new HttpCookie("lang", e.CommandArgument.ToString());
        Response.SetCookie(cok);

        System.Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.GetCultureInfo(e.CommandArgument.ToString());

        btnNext.Text = Resources.Language.INext;
        cbUseConnectionEditForm.Text = Resources.Language.IYesIWantToFillTheForm;
        lbBack.Text = Resources.Language.Back;
        lbInstallationProblems.Text = Resources.Language.InstallationProblems;

    }

    protected void lbInstallationProblems_OnClick(object sender, EventArgs e)
    {
        CurrentPage = -1;
    }

    protected void lbBack_OnClick(object sender, EventArgs e)
    {
        CurrentPage = 1;
    }

    #endregion EVENTS

    #region PAGE EVENTS

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            switch (CommonTools.GetInstallationStatus())
            {
                case CommonTools.InstallationStatus.NotInstalled:
                    CurrentPage = 1;
                    break;
                case CommonTools.InstallationStatus.Installed:
                    CurrentPage = 7;
                    Response.Redirect("~/Default.aspx");
                    break;
            }
        }
    }

    protected void Page_LoadComplete(object sender, EventArgs e)
    {
        if (CurrentPage > 0)
            lblStep.Text = String.Format("{0} {1}/7", Resources.Language.IStep, CurrentPage);
        else
            lblStep.Text = Resources.Language.ManualInstallation;

        pnlStep1.Visible = CurrentPage == 1;
        pnlStep2.Visible = CurrentPage == 2;
        pnlStep3.Visible = CurrentPage == 3;
        pnlStep4.Visible = CurrentPage == 4;
        pnlStep5.Visible = CurrentPage == 5;
        pnlStep6.Visible = CurrentPage == 6;
        pnlStep7.Visible = CurrentPage == 7;
        pnlManualInstallaiton.Visible = CurrentPage == -1;
        lbInstallationProblems.Visible = CurrentPage > 0;
        lbBack.Visible = CurrentPage == -1;
        lblStep.Visible = CurrentPage == -1;
        cNext.Visible = CurrentPage > 0;

        switch (CurrentPage)
        {
            case 3:
                btnNext.ValidationGroup = "ConnectionString";
                break;
            case 5:
                btnNext.ValidationGroup = "CreateAdmin";
                break;
            case 6:
                btnNext.ValidationGroup = "Config";
                break;
            default:
                btnNext.ValidationGroup = "";
                break;
        }
    }

    #endregion PAGE EVENTS
}
